package cn.tm.liu.mvc.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Marvin.L
 * @description
 * @date 2022.03.30 09.31
 */
@Slf4j
public class HttpResult implements Serializable {

    private static final long serialVersionUID = -6090471597368455439L;

    private Integer code;
    private String message;
    private Object data;
    private Object extra;

    public Integer getCode() {
        return code;
    }

    public HttpResult setCode(Integer code) {
        this.code = code;
        return this;
    }

    public String getMessage() {
        return message;
    }

    public HttpResult setMessage(String message) {
        this.message = message;
        return this;
    }

    public Object getData() {
        return data;
    }

    public Object getExtra() {
        return extra;
    }

    private HttpResult setExtra(Object extra) {
        this.extra = extra;
        return this;
    }

    public HttpResult extra() {
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest req = attr.getRequest();
        this.setExtra(new HashMap() {{
            put("begin", req.getAttribute(ResponseResult.REQUEST_BEGIN));
            put("over", new Date());
        }});
        return this;
    }

    private ResultCode resultCode;

    public HttpResult setData(Object data) {
        this.data = data;
        return this;
    }

    private HttpResult setResultCode(ResultCode resultCode) {
        this.code = resultCode.code();
        this.message = resultCode.message();
        return this;
    }

    public HttpResult() {
    }

    public static HttpResult success() {
        HttpResult result = new HttpResult();
        result.setResultCode(ResultCode.SUCCESS);
        return result;
    }

    public static HttpResult success(Object data) {
        if (data instanceof Collection) {
            final Collection collection = (Collection) data;
            Map map = new HashMap();
            map.put("array", collection);
            map.put("size", collection.size());
            return success().setData(map);
        } else {
            log.info(data.getClass().getName());
            return success().setData(data);
        }
    }

    public static HttpResult failure() {
        HttpResult result = new HttpResult();
        result.setResultCode(ResultCode.FAILURE);
        return result;
    }

    public static HttpResult failure(Object object) {
        HttpResult result = failure();
        result.setData(object);
        return result;
    }
}
